package com.art.servlet;

import com.art.service.UserService;
import com.art.service.impl.UserServiceImpl;
import com.art.utils.ThymeleafUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.context.Context;

import java.io.IOException;

/**
 * IntelliJ IDEA
 *
 * @author 谭礼赞 2038940123
 * @since 2022-11-07-2022/11/7
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {

    UserService service;
    @Override
    public void init() throws ServletException {
        service=new UserServiceImpl ();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Context context=new Context();
        if(req.getSession ().getAttribute ( "login-failure" )!=null){
            context.setVariable ( "failure",true );
            req.getSession ().removeAttribute ( "login-failure" );
        }
        //ThymeleafUtil.process ( "login.html",new Context (),resp.getWriter () );
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uname =req.getParameter("uname");
        String pwd =req.getParameter("pwd");
        String remenber =req.getParameter("remenber-me");
        //若登录成功，则跳转到首页
        if(service.auth ( uname,pwd,req.getSession () )){
            resp.sendRedirect ( "index.jsp" );
        }else{
            //添加登录失败标记
            req.getSession().setAttribute ( "login-failure",new Object () );
            //this.doGet ( req,resp );
            //resp.sendRedirect ( "index.jsp" );
        }
    }
}
